package com.client
{
	import com.client.event.XMLEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	[Event(name="XMLEvent", type="com.client.event.XMLEvent")]
	
	/**
	 * XML加载器
	 * @author Tide
	 */
	public class XMLLoader extends EventDispatcher
	{
		private var _stream:URLStream;
		private var _isCompress:Boolean = false;
		public function XMLLoader()
		{
			initLoader();
		}
		
		private function initLoader():void
		{
			_stream = new URLStream();
			_stream.addEventListener(Event.OPEN,onOpen);
			_stream.addEventListener(Event.COMPLETE,onComplete);
			_stream.addEventListener(ProgressEvent.PROGRESS,onProgressHandler);
			_stream.addEventListener(IOErrorEvent.IO_ERROR,onIoError);
			_stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);
		}
		
		public function load(url:String,isCompress:Boolean=false):void
		{
			_stream.load(new URLRequest(url));
			_isCompress = isCompress;
		}
		
		public function close():void
		{
			if(_stream.connected)
				_stream.close();
		}
		
		public function destroy():void
		{
			_stream.removeEventListener(Event.OPEN,onOpen);
			_stream.removeEventListener(Event.COMPLETE,onComplete);
			_stream.removeEventListener(ProgressEvent.PROGRESS,onProgressHandler);
			_stream.removeEventListener(IOErrorEvent.IO_ERROR,onIoError);
			_stream.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);
			_stream = null;
		}
		
		private function onOpen(event:Event):void
		{
			dispatchEvent(event);
		}
		
		private function onProgressHandler(event:ProgressEvent):void
		{
			dispatchEvent(event);
		}
		
		private function onComplete(event:Event):void
		{
			var data:ByteArray = new ByteArray();
			_stream.readBytes(data);
			if(_isCompress)
				data.uncompress();
			dispatchEvent(new XMLEvent(XMLEvent.COMPLETE,XML(data.readUTFBytes(data.bytesAvailable))));
		}
		
		private function onIoError(event:IOErrorEvent):void
		{
			dispatchEvent(event);
			throw new Error(event.text);
		}
		
		private function onSecurityError(event:SecurityErrorEvent):void
		{
			dispatchEvent(event);
			throw new SecurityError(event.text);
		}
	}
}